<template>
  <div class="profile-container">
    <header class="header">
      <h1>个人中心</h1>
      <nav>
        <router-link to="/" class="nav-link">返回首页</router-link>
        <button @click="handleLogout" class="logout-btn">退出登录</button>
      </nav>
    </header>

    <main class="main-content">
      <div class="profile-card" v-if="userInfo">
        <div class="avatar-section">
          <div class="avatar-wrapper">
            <img v-if="avatarUrl" :src="avatarUrl" alt="头像" class="avatar-img" />
            <div v-else class="avatar">
              {{ userInfo.nickname?.charAt(0) || userInfo.username?.charAt(0) || 'U' }}
            </div>
            <div class="avatar-overlay">
              <input
                type="file"
                ref="avatarInput"
                @change="handleAvatarChange"
                accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                style="display: none"
              />
              <button @click="selectAvatar" class="upload-btn" :disabled="uploading">
                {{ uploading ? '上传中...' : '更换头像' }}
              </button>
            </div>
          </div>
        </div>

        <div class="info-section">
          <h2>{{ userInfo.nickname || userInfo.username }}</h2>

          <div class="info-list">
            <div class="info-item">
              <span class="label">用户名：</span>
              <span class="value">{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
              <span class="label">邮箱：</span>
              <span class="value">{{ userInfo.email }}</span>
            </div>
            <div class="info-item" v-if="userInfo.phone">
              <span class="label">手机号：</span>
              <span class="value">{{ userInfo.phone }}</span>
            </div>
            <div class="info-item">
              <span class="label">状态：</span>
              <span class="value" :class="statusClass">{{ statusText }}</span>
            </div>
            <div class="info-item">
              <span class="label">注册时间：</span>
              <span class="value">{{ formatDate(userInfo.created_at) }}</span>
            </div>
            <div class="info-item" v-if="userInfo.last_login">
              <span class="label">最后登录：</span>
              <span class="value">{{ formatDate(userInfo.last_login) }}</span>
            </div>
          </div>

          <button @click="refreshProfile" class="refresh-btn" :disabled="loading">
            {{ loading ? '刷新中...' : '刷新信息' }}
          </button>
        </div>
      </div>
    </main>

    <Loading :show="loading" text="加载中..." />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { getProfile, logout, updateProfile } from '@/api/auth'
import { uploadAvatar } from '@/api/upload'
import message from '@/utils/message'
import Loading from '@/components/Loading.vue'

const router = useRouter()
const authStore = useAuthStore()

const userInfo = ref(null)
const loading = ref(false)
const uploading = ref(false)
const avatarInput = ref(null)

// 头像 URL (优先显示用户的头像，否则显示默认)
const avatarUrl = computed(() => {
  // API 返回的字段可能是 avatar 或 avatar_url
  return userInfo.value?.avatar || userInfo.value?.avatar_url || null
})

const statusClass = computed(() => {
  return userInfo.value?.status === 'active' ? 'status-active' : 'status-inactive'
})

const statusText = computed(() => {
  return userInfo.value?.status === 'active' ? '正常' : '禁用'
})

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const fetchProfile = async () => {
  try {
    loading.value = true
    const response = await getProfile()
    if (response.code === 200) {
      userInfo.value = response.data
      authStore.updateUser(response.data)
    }
  } catch (error) {
    message.error(error.message || '获取用户信息失败')
  } finally {
    loading.value = false
  }
}

const refreshProfile = () => {
  fetchProfile()
}

// 选择头像文件
const selectAvatar = () => {
  avatarInput.value?.click()
}

// 处理头像文件选择
const handleAvatarChange = async (event) => {
  const file = event.target.files?.[0]
  if (!file) return

  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
  if (!allowedTypes.includes(file.type)) {
    message.error('请选择 JPG、PNG、GIF 或 WEBP 格式的图片')
    return
  }

  // 验证文件大小 (2MB)
  const maxSize = 2 * 1024 * 1024
  if (file.size > maxSize) {
    message.error('图片大小不能超过 2MB')
    return
  }

  try {
    uploading.value = true

    // 1. 上传头像到 MinIO
    const uploadResponse = await uploadAvatar(file)

    if (uploadResponse.code === 200) {
      // 2. 获取文件路径（不是 URL）
      const filePath = uploadResponse.data.image?.file_path

      if (!filePath) {
        message.error('上传成功但未获取到文件路径')
        return
      }

      // 3. 调用更新用户资料接口，将头像路径写入数据库
      const updateResponse = await updateProfile({ avatar: filePath })

      if (updateResponse.code === 200) {
        message.success('头像更新成功')

        // 4. 更新本地状态（使用接口返回的完整用户信息）
        userInfo.value = updateResponse.data
        authStore.updateUser(updateResponse.data)
      }
    }
  } catch (error) {
    message.error(error.message || '头像上传失败')
  } finally {
    uploading.value = false
    // 清空文件选择，允许重复选择同一文件
    if (avatarInput.value) {
      avatarInput.value.value = ''
    }
  }
}

const handleLogout = async () => {
  try {
    await logout()
    authStore.logout()
    message.success('退出登录成功')
    router.push('/login')
  } catch (error) {
    message.error(error.message || '退出登录失败')
  }
}

onMounted(() => {
  // 如果 store 中有用户信息，直接显示
  if (authStore.user) {
    userInfo.value = authStore.user
  } else {
    // 只有当 store 中没有用户信息时才请求
    fetchProfile()
  }
})
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.header {
  background: white;
  padding: 20px 40px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

nav {
  display: flex;
  gap: 20px;
  align-items: center;
}

.nav-link {
  text-decoration: none;
  color: #667eea;
  font-weight: 500;
  transition: color 0.3s;
}

.nav-link:hover {
  color: #764ba2;
}

.logout-btn {
  padding: 8px 16px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.logout-btn:hover {
  background: #fff;
  border-color: #667eea;
  color: #667eea;
}

.main-content {
  flex: 1;
  padding: 40px;
  display: flex;
  justify-content: center;
}

.profile-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  max-width: 600px;
  width: 100%;
}

.avatar-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px;
  display: flex;
  justify-content: center;
}

.avatar-wrapper {
  position: relative;
  width: 120px;
  height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: white;
  color: #667eea;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 48px;
  font-weight: bold;
}

.avatar-img {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  background: white;
  border: 3px solid white;
}

.avatar-overlay {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.upload-btn {
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.95);
  color: #667eea;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.upload-btn:hover:not(:disabled) {
  background: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.upload-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.info-section {
  padding: 30px 40px;
}

.info-section h2 {
  margin: 0 0 30px 0;
  text-align: center;
  color: #333;
  font-size: 28px;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item .label {
  color: #666;
  font-weight: 500;
}

.info-item .value {
  color: #333;
}

.status-active {
  color: #52c41a;
}

.status-inactive {
  color: #ff4d4f;
}

.refresh-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: opacity 0.3s;
}

.refresh-btn:hover:not(:disabled) {
  opacity: 0.9;
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>